#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/7/14
# @Author  : LiJun
# @Email   : lijun@tianyancha.com
# @Version : 1.0.0
import json
import re

import mitmproxy.http
from mitmproxy import ctx


class Rewrite:

    def response(self, flow: mitmproxy.http.HTTPFlow):
        """
            The full HTTP response has been read.
        """
        if "https://stock.xueqiu.com/v5/stock/batch/quote.json?_t=" in flow.request.pretty_url and "x=" in flow.request.pretty_url:
            # ctx.log.info(f"==========\n {flow.response.text}")
            response_data = json.loads(flow.response.text)
            response_data['data']['items'][0]['quote']['name'] = "奶粉钱_rewrite"
            response_data['data']['items'][0]['quote']['percent'] = 0.0
            response_data['data']['items'][1]['quote']['percent'] = +1.0
            response_data['data']['items'][2]['quote']['percent'] = -2.0

            response_text = json.dumps(response_data)

            re_pattern = r'^([-]|[+])?[0-9]+\.?[0-9]+$'
            temp = re.compile(re_pattern)
            t_list = temp.findall(response_text)
            ctx.log.info(f"----------\n {response_text}")
            ctx.log.info(f"----------\n {len(t_list)}")

            # flow.response.text = re.sub(re_pattern, response_text)

    def multiple_float(self, data, multiple=1):
        if isinstance(data, dict):
            for k, v in data.items():
                data[k] = self.multiple_float(v, multiple)
        elif isinstance(data, list):
            data = [self.multiple_float(i, multiple=multiple) for i in data]
        elif isinstance(data, float):
            data = data * multiple
        else:
            data = data
        return data


addons = [
    Rewrite()
]

if __name__ == '__main__':
    # from mitmproxy.tools.main import mitmdump
    #
    # mitmdump(['-p', '8080', '-s', __file__])

    a = r'^([-]|[+])?[0-9]+\.?[0-9]+$'
    str1 = '{"data": {"items": [{"market": {"status_id": 1, "region": "CN", "status": "\u672a\u5f00\u76d8", "time_zone": "Asia/Shanghai", "time_zone_desc": null, "delay_tag": 0}, "quote": {"symbol": "SH601318", "code": "601318", "exchange": "SH", "name": "\u5976\u7c89\u94b1_rewrite", "type": 11, "sub_type": "ASH", "status": 1, "current": 57.91, "currency": "CNY", "percent": 0.0, "chg": -1.79, "timestamp": 1626246000000, "time": 1626246000000, "lot_size": 100, "tick_size": 0.01, "open": 59.65, "last_close": 59.7, "high": 59.65, "low": 57.78, "avg_price": 58.181, "volume": 106561835, "amount": 6199867459.0, "turnover_rate": 0.98, "amplitude": 3.13, "market_capital": 1058608780053.0, "float_market_capital": 627319601079.0, "total_shares": 18280241410, "float_shares": 10832664498, "issue_date": 1172678400000, "lock_set": null, "current_year_percent": -32.16, "high52w": 92.8649, "low52w": 57.78, "limit_up": 65.67, "limit_down": 53.73, "volume_ratio": 1.57, "eps": 7.89, "pe_ttm": 7.338, "pe_forecast": 9.722, "pe_lyr": 7.398, "navps": 42.24, "pb": 1.371, "dividend": 2.2, "dividend_yield": 3.799, "profit": 143099000000.0, "profit_four": 144259000000.0, "profit_forecast": 108892000000.0, "pledge_ratio": 3.17, "goodwill_in_net_assets": 3.0222267116821357, "timestamp_ext": null, "current_ext": null, "volume_ext": null, "traded_amount_ext": null, "no_profit": null, "no_profit_desc": null, "weighted_voting_rights": null, "weighted_voting_rights_desc": null, "is_registration": null, "is_registration_desc": null, "is_vie": null, "is_vie_desc": null, "security_status": null}, "others": {"cyb_switch": true}, "tags": []}, {"market": {"status_id": 1, "region": "CN", "status": "\u672a\u5f00\u76d8", "time_zone": "Asia/Shanghai", "time_zone_desc": null, "delay_tag": 0}, "quote": {"symbol": "SH601919", "code": "601919", "exchange": "SH", "name": "XR\u4e2d\u8fdc\u6d77", "type": 11, "sub_type": "ASH", "status": 1, "current": 23.16, "currency": "CNY", "percent": 1.0, "chg": -0.59, "timestamp": 1626246000000, "time": 1626246000000, "lot_size": 100, "tick_size": 0.01, "open": 24.0, "last_close": 23.75, "high": 24.15, "low": 22.85, "avg_price": 23.45, "volume": 215574006, "amount": 5055217386.0, "turnover_rate": 2.47, "amplitude": 5.47, "market_capital": 370810094557.0, "float_market_capital": 201810946875.0, "total_shares": 16010798556, "float_shares": 8713771454, "issue_date": 1182787200000, "lock_set": null, "current_year_percent": 146.58, "high52w": 25.6923, "low52w": 2.9923, "limit_up": 26.13, "limit_down": 21.38, "volume_ratio": 0.63, "eps": 1.57, "pe_ttm": 14.78, "pe_forecast": 5.999, "pe_lyr": 37.353, "navps": 3.71, "pb": 6.243, "dividend": 0.0, "dividend_yield": 0.0, "profit": 9927098239.01, "profit_four": 25087910610.28, "profit_forecast": 61809327351.0, "pledge_ratio": null, "goodwill_in_net_assets": 9.796450282176236, "timestamp_ext": null, "current_ext": null, "volume_ext": null, "traded_amount_ext": null, "no_profit": null, "no_profit_desc": null, "weighted_voting_rights": null, "weighted_voting_rights_desc": null, "is_registration": null, "is_registration_desc": null, "is_vie": null, "is_vie_desc": null, "security_status": null}, "others": {"cyb_switch": true}, "tags": []}, {"market": {"status_id": 5, "region": "US", "status": "\u4ea4\u6613\u4e2d", "time_zone": "America/New_York", "time_zone_desc": null, "delay_tag": 0}, "quote": {"symbol": "DIDI", "code": "DIDI", "exchange": "NYSE", "name": "\u6ef4\u6ef4", "type": 0, "sub_type": null, "status": 1, "current": 12.96, "currency": "USD", "percent": -2.0, "chg": 0.54, "timestamp": 1626279460235, "time": 1626279460235, "lot_size": 1, "tick_size": 0.01, "open": 12.51, "last_close": 12.42, "high": 13.11, "low": 11.97, "avg_price": 12.6231, "volume": 39571226, "amount": 499182951.9239, "turnover_rate": 0.82, "amplitude": 9.18, "market_capital": 62509209529.0, "float_market_capital": null, "total_shares": 4823241476, "float_shares": null, "issue_date": 1624982400000, "lock_set": null, "current_year_percent": -7.43, "high52w": 18.01, "low52w": 11.0, "variable_tick_size": "0.0001 1 0.01", "volume_ratio": 1.08, "eps": -0.04175490585053741, "pe_ttm": -310.383, "pe_lyr": -37.8694, "navps": null, "pb": -5.784, "dividend": null, "dividend_yield": null, "psr": 2.2, "short_ratio": null, "inst_hld": null, "beta": null, "timestamp_ext": 1626269399025, "current_ext": 12.52, "percent_ext": 0.8052, "chg_ext": 0.1, "contract_size": 100, "pe_forecast": 18.742, "profit_forecast": 3335307810.01252, "profit": -1650650705.5750477, "profit_four": -201393993.72478712, "pledge_ratio": null, "goodwill_in_net_assets": -69.96222463291683, "shareholder_funds": -10807239060.881931}, "others": {"cyb_switch": true}, "tags": []}], "items_size": 3}, "error_code": 0, "error_description": ""}'

    pattern = re.compile(a, re.M)
    print(pattern.search(str1))
